//
//  HomePageViewController.m
//  Food & Delights
//
//  Created by dlios on 15-7-13.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "HomePageViewController.h"
#import "ScrollImageView.h"
#import "AFNet.h"
#import "BaseHeader.h"
#import "HomePageModel.h"
#import "AppDelegate.h"
#import "LeftViewController.h"
#import "ShufflingCollectionViewCell.h"
#import "RecommendedCollectionViewCell.h"
#import "ThreeMealsViewController.h"
#import "shufflingModel.h"
#import "RecommendModel.h"
#import "ThreeViewDetailsViewController.h"
#import "ThreeBtnViewController.h"
#import "AppDelegate.h"
#import "landingViewController.h"
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

@interface HomePageViewController ()<Mydelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MBProgressHUDDelegate>

@property (nonatomic, retain) UILabel *lblRecommend;
@end

@implementation HomePageViewController

- (void)dealloc
{
    [_arrShuffling release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrFooter = [NSMutableArray array];
        self.arrHeader = [NSMutableArray array];
        self.arrRecommend = [NSMutableArray array];
        self.headerRe = [[UICollectionReusableView alloc] init];
        self.header = [[UICollectionReusableView alloc] init];
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    [self.navigationItem setLeftBarButtonItem:nil animated:NO];
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    self.progress.hidden = YES;
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        return;
    }
    [self createProgress];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-shouyezuoshangchoutilan"] imageWithRenderingMode: UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(show)];
    [self getDataShuffling];
    [self createHeaderText];
    [self.navigationItem.leftBarButtonItem release];
}

#pragma 创建主collectionView
- (void)creatMainView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.mainCollection = [[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 44) collectionViewLayout:layout] autorelease];
    self.mainCollection.backgroundColor = RGBCOLOR(239, 248, 237);
    self.mainCollection.delegate = self;
    self.mainCollection.dataSource = self;
    [self.mainCollection registerClass:[ShufflingCollectionViewCell class] forCellWithReuseIdentifier:@"shuffling"];
    [self.mainCollection registerClass:[RecommendedCollectionViewCell class] forCellWithReuseIdentifier:@"recommend"];
    [self.mainCollection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.mainCollection registerClass:[self.headerRe class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerRe"];
    [self.view addSubview:self.mainCollection];
    [self.mainCollection release];
    // 创建精选title
    self.lblRecommend = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, SCREEN_WIDTH, 30)];
    self.lblRecommend.backgroundColor = [UIColor whiteColor];
        _lblRecommend.textAlignment = NSTextAlignmentCenter;
    [self.lblRecommend release];
    // 轮播图创建
    self.my = [[ScrollImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200) withImageArray:self.arrShuffling];
    self.my.delegate = self;
    [self.my release];
}
#pragma mark - 菊花
- (void)createProgress
{
    self.progress = [[MBProgressHUD alloc] initWithView:self.view];
    self.progress.labelText = @"稍等";
    self.progress.detailsLabelText = @"正在加载...";
    self.progress.delegate = self;
    [self.progress show:YES];
    [self.view addSubview:self.progress];
}

- (void)doSomething
{
    //你要进行的一些事
    sleep(2);
}

#pragma mark - 创建轮播图视图并解析数据
- (void)getDataShuffling
{

    self.arrShuffling = [NSMutableArray array];
    [AFNet connectNetGetDataWithURLString:ThreeMeals parameters:nil finishblock:^(id result) {
            self.progress.hidden = YES;
        Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
        if (r.currentReachabilityStatus == NotReachable) {
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alert1 show];
            [alert1 release];
            return;
        }
        NSDictionary *dicTemp = result[@"data"];
        NSArray *arr = dicTemp[@"recommend"];
        NSDictionary *dicTime = dicTemp[@"whatHour"];
        self.strTime = dicTime[@"title"];
        for (NSDictionary *d in arr) {
            HomePageModel *model = [[[HomePageModel alloc] initWithDic:d] autorelease];
            [self.arrShuffling addObject:model];
        }
        [self getDataRecommend];
    }];

}

#pragma mark - 精品推荐数据解析
- (void)getDataRecommend
{

    [AFNet connectNetGetDataWithURLString:Recommend parameters:nil finishblock:^(id result) {
        Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
        if (r.currentReachabilityStatus == NotReachable) {
            UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alert1 show];
            [alert1 release];
            return;
        }
        NSDictionary *dic = result[@"data"];
        NSArray *arr = dic[@"dishs"];
        for (NSDictionary *d in arr) {
            RecommendModel *model = [[[RecommendModel alloc] initWithDic:d] autorelease];
            [self.arrRecommend addObject:model];
        }
        [self creatMainView];
        [self creatView:self.arrShuffling];
        [self setUpReFresh];
    }];
}

#pragma mark - 刷新与拉取
- (void)setUpReFresh
{
    // 下拉刷新
    [self.mainCollection addHeaderWithTarget:self action:@selector(headerRereshing)];
    // 上拉加载
    [self.mainCollection addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.mainCollection headerBeginRefreshing];
    // 设置文字
    self.mainCollection.headerPullToRefreshText = @"下拉刷新";
    self.mainCollection.headerReleaseToRefreshText = @"松开立刻刷新";
    self.mainCollection.headerRefreshingText = @"刷新中,请稍后...";

    self.mainCollection.footerPullToRefreshText = @"上拉加载数据";
    self.mainCollection.footerReleaseToRefreshText = @"松开立刻加载数据";
    self.mainCollection.footerRefreshingText = @"加载数据中,请稍后...";
}

#pragma mark - 下拉刷新方法
-(void)headerRereshing
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        return;
    }
    [self.arrHeader removeAllObjects];
    [AFNet connectNetGetDataWithURLString:Recommend parameters:nil finishblock:^(id result) {
        NSDictionary *dic = result[@"data"];
        NSArray *arr = dic[@"dishs"];
        for (NSDictionary *d in arr) {
            RecommendModel *model = [[RecommendModel alloc] initWithDic:d];
            [self.arrHeader addObject:model];
        }
        [self.arrRecommend removeAllObjects];
        [self.arrRecommend addObjectsFromArray:self.arrHeader];
    }];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.mainCollection reloadData];
        [self.mainCollection headerEndRefreshing];
    });
    self.page = 2;
}
#pragma mark - 上拉加载
- (void)footerRereshing
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
        [alert1 release];
        return;
    }
    [self.arrFooter removeAllObjects];
    NSString *str1 = @"http://api.xiangha.com/caipu5/getDishList?page=";
    NSString *str2 = @"&g1=1705&type=caidan";
    NSString *str3 = [NSString stringWithFormat:@"%@%ld%@", str1, self.page++, str2];
    [AFNet connectNetGetDataWithURLString:str3 parameters:nil finishblock:^(id result) {
        NSDictionary *dic = result[@"data"];
        NSArray *arr = dic[@"dishs"];
        for (NSDictionary *d in arr) {
            RecommendModel *model = [[RecommendModel alloc] initWithDic:d];
            [self.arrFooter addObject:model];
            [model release];
        }
        [self.arrRecommend addObjectsFromArray:self.arrFooter];
        [self.mainCollection reloadData];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.mainCollection reloadData];
        [self.mainCollection footerEndRefreshing];
    });
}

#pragma mark - collectionView头部设置
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (kind == UICollectionElementKindSectionHeader) {
            self.header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
            self.header.backgroundColor = [UIColor whiteColor];
            [self creatView:self.arrShuffling];
            return self.header;
        }
    } if (indexPath.section == 1) {
        self.headerRe = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerRe" forIndexPath:indexPath];
        [self createHeaderText];
        return self.headerRe;
    }
    return 0;
}

#pragma mark - 精品推荐title
- (void)createHeaderText
{
    _lblRecommend.text = @"精品推荐";
    [self.headerRe addSubview:self.lblRecommend];
}
#pragma mark - 轮播图视图创建
- (void)creatView:(NSMutableArray *)arr
{
    [self.header addSubview:self.my];
}
#pragma mark - 轮播图协议跳转
- (void)pushToNextControllerWithIDName:(NSString *)name
{
    ThreeMealsViewController *threeMeal = [[ThreeMealsViewController alloc] init];
    threeMeal.strType = name;
    threeMeal.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:threeMeal animated:YES];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

#pragma mark - collectionView区的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    } else if(section == 1) {
        return self.arrRecommend.count;
    }
    return 1;
}
#pragma mark - collectionViewCell设置
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ShufflingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"shuffling" forIndexPath:indexPath];
        // 首页三个button显示数据
        shufflingModel *model1 = [[[shufflingModel alloc] init] autorelease];
        model1.title = @"精选";
        model1.pic = @"btn1";
        shufflingModel *model2 = [[[shufflingModel alloc] init] autorelease];
        model2.title = @"技巧";
        model2.pic = @"btn2";
        shufflingModel *model3 = [[[shufflingModel alloc] init] autorelease];
        model3.title = @"杂谈";
        model3.pic = @"btn3";
        NSArray *arr = @[model1, model2, model3];

        cell.shuffModel = arr[indexPath.row];
        return cell;
    } else if(indexPath.section == 1) {
        RecommendedCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"recommend" forIndexPath:indexPath];
        cell.model = self.arrRecommend[indexPath.row];
        return cell;
    }
    return nil;
}

#pragma mark - header区域大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(SCREEN_WIDTH - 20, 200);
    } else if(section == 1){
        return CGSizeMake(320, 40);
    }
    return CGSizeMake(0, 0);
}

#pragma mark - 自定义CollectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
// 精选, 烹饪技巧, 美食杂谈
        ThreeBtnViewController *threeBtn = [[[ThreeBtnViewController alloc] init] autorelease];
        threeBtn.hidesBottomBarWhenPushed = YES;
        if (indexPath.item == 0) {
            threeBtn.strHttp = SELECT;
            threeBtn.btnInt = 0;

        } else if (indexPath.item == 1) {
            threeBtn.strHttp = COOKING;
            threeBtn.btnInt = 1;
        } else {
            threeBtn.strHttp = TALKING;
            threeBtn.btnInt = 2;

        }
        [self.navigationController pushViewController:threeBtn animated:YES];

    } else {
        ThreeViewDetailsViewController *select = [[[ThreeViewDetailsViewController alloc] init] autorelease];
        select.Code = [self.arrRecommend[indexPath.item] code];
        select.strImg = [self.arrRecommend[indexPath.item] img];
        select.judge = 2;
        select.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:select animated:YES];
    }
}



#pragma mark - section边界间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsMake(10, 20, 0, 20);
    } else if(section == 1) {
        return UIEdgeInsetsMake(0, 0, 30, 0);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
#pragma mark - item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(80, 100);
    } else if (indexPath.section == 1) {
        return CGSizeMake(320, 200);
    }
    return CGSizeMake(0, 0);
}

- (void)show
{
    [self showMenu];
}
//抽屉
- (void)showMenu
{
    if (!_sideMenu) {
        RESideMenuItem *more = [[RESideMenuItem alloc] initWithTitle:@"更多" action:^(RESideMenu *menu, RESideMenuItem *item) {

        }];

        RESideMenuItem *landing = [[RESideMenuItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"iconfont-wode"] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            self.hidesBottomBarWhenPushed = NO;
            self.navigationController.navigationBarHidden = NO;
            landingViewController *land = [[landingViewController alloc] init];
            UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:land];
            land.title = item.title;
            [menu setRootViewController:navi];
        }];

        RESideMenuItem *returnMain = [[RESideMenuItem alloc] initWithTitle:@"返回主页" image:[UIImage imageNamed:@"iconfont-zhuye"] highlightedImage:nil action:^(RESideMenu *menu, RESideMenuItem *item) {
            AppDelegate *app = [UIApplication sharedApplication].delegate;
            [menu setRootViewController:app.rootTBC];
        }];
        _sideMenu = [[RESideMenu alloc] initWithItems:@[more, landing, returnMain]];
        _sideMenu.verticalOffset = IS_WIDESCREEN ? 20 : 20;
        _sideMenu.hideStatusBarArea = [AppDelegate OSVersion] < 3;
    }
    [_sideMenu show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
